package org.example.reggie.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.example.reggie.common.BaseContext;
import org.example.reggie.common.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        log.info("拦截到请求：{}", request.getRequestURI());
        String uri = request.getRequestURI();
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };
        if(check(urls, uri)) {
            log.info("本次请求{}不需要处理", uri);
            filterChain.doFilter(request, response);
            return;
        }
        //判断后台登录
        if(request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录");
            Long id = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrent(id);
            filterChain.doFilter(request, response);
            return;
        }
        //判断移动端登录
        if(request.getSession().getAttribute("user") != null) {
            log.info("用户已登录");
            Long id = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrent(id);
            filterChain.doFilter(request, response);
            return;
        }
        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    private boolean check(String[] urls, String uri) {
        for (String url : urls) {
            if(PATH_MATCHER.match(url, uri)) {
                return true;
            }
        }
        return false;
    }
}
